package com.jyx.web.tcp;

import java.net.*;
import java.io.*;
public class TCPServer {
	public static void main(String[] args) throws Exception{
		ServerSocket ss=new ServerSocket(9000);//端口号
		while(true){
			Socket s=ss.accept();//连接监听客户端
			System.out.println(s.getInetAddress());
			Thread t=new ServerThread(s);//实现多线程连接
			t.start();
		}
	}
}
class ServerThread extends Thread{//分配线程
	Socket s;
	public ServerThread(Socket s){
		this.s=s;
	}
	public void run(){
		try {
			OutputStream os=s.getOutputStream();//在网络中获取输出流
			PrintWriter out=new PrintWriter(os);
			for(int i=1;i<=30;i++){
			out.println("Hello "+i);//通过网络发消息给客户端
			out.flush();
			Thread.sleep(1000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				s.close();//注意关闭线程而不关闭流
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
